package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.处理普通用户登录
        if(StringUtils.isNotBlank(loginDto.getPhone())&&StringUtils.isNotBlank(loginDto.getPassword())){
            //1.1 判断账户是否存在
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在" );
            }

            String apUserPassword = apUser.getPassword();
            String loginDtoPassword = loginDto.getPassword();
            boolean result = BCrypt.checkpw(loginDtoPassword, apUserPassword);
            //1.2 判断密码是否正确
            if(!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 返回请求数据
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            apUser.setPassword("");
            Map resultmap=new HashMap();
            resultmap.put("token", token);
            resultmap.put("apUser", apUser);
            return ResponseResult.okResult(resultmap);

        }else {
            //2.访客用户登录
            String token = AppJwtUtil.getToken(0l);
            Map map=new HashMap();
            map.put("token", token);
            return  ResponseResult.okResult(map);
        }


    }
}
